<?php

namespace App\Http\Controllers\Index;

use App\Exceptions\ResponseException;
use App\Models\Prize;
use App\Models\UserPrize;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Whoops\Exception\ErrorException;

class PrizeController extends Controller
{
	protected $prizeArr = [];//抽奖的数组
	protected $prizeMap = [];//映射奖品id和名字
	protected $prizeTicketCount = 0;//奖池总数

	public function __construct(){
		//从缓存里面取奖品构成的数组没有就生成，有的话就直接取
		$prizeModel = new Prize();
		$this->prizeArr = $prizeModel->getPrizeArrFromCache();
		if($this->prizeArr){
			$this->prizeMap = \Cache::get('prizeMap');
			$this->prizeTicketCount = \Cache::get('prizeTicketCount');
		}
	}

	/**
	 * 抽奖
	 * User: ihome
	 * @throws ResponseException
	 */
	public function getPrize()
    {
		if($this->prizeArr){
			//生成随机数
			$randNum = mt_rand(0,$this->prizeTicketCount-1);

			$prize = $this->prizeArr[$randNum];

			//判断是否为谢谢惠顾
			if($prize != '谢谢惠顾'){
			    //查找商品
				$prizeId = array_search($prize,$this->prizeMap);

				//判断奖池的数量
				$prizeInfo = Prize::query()->select('*')->find($prizeId,'id');

				//开启事务
				\DB::beginTransaction();
				if($prizeInfo && $prizeInfo['prize_num'] > 0){
					try{
						//更新到用户中奖表
						$user_prize = new UserPrize();
						$user_prize->fill([
							'user_id'=>1,
							'prize_id'=>$prizeId,
						]);
						$user_prize->save();

						//TODO 添加锁机制

						//减少数量
						Prize::query()->where('id',$prizeId)->decrement('prize_num',1);

						\DB::commit();
						throw new ResponseException('200','恭喜您抽中了:' . $prize,[
							'count'=>$this->prizeTicketCount,
							'randNum'=>$randNum
						]);
					}catch (ErrorException $e){
						\DB::rollBack();
						//写入日志记录
						\Log::info($e->getMessage());
						throw new ResponseException('500','抽奖失败，请联系管理员');
					}
				}else{
					throw new ResponseException('200','ok',['msg'=>'谢谢惠顾','data'=>$prizeInfo]);
				}
			}else{
				throw new ResponseException('200','ok',['msg'=>'谢谢惠顾']);
			}
		}else{
			throw new ResponseException('404','抽奖功能暂停使用');
		}
    }
}
